package com.sky.common.exception;

import com.sky.utils.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class GlobalExceptionHandler {

    //1 全局异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        System.out.println("全局....");
        e.printStackTrace();
        return Result.error().message("执行了全局异常处理");
    }

    //2 特定异常处理
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result error(ArithmeticException e) {
        System.out.println("特定......");
        e.printStackTrace();
        return Result.error().message("执行了特定异常处理");
    }

    //3 自定义异常处理
    @ExceptionHandler(SkyException.class)
    @ResponseBody
    public Result error(SkyException e) {
        e.printStackTrace();
        return Result.error().code(e.getCode()).message(e.getMsg());
    }

    /**
     * spring security异常 security 抛出
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SkySecurityException.class)
    @ResponseBody
    public Result error(SkySecurityException e) throws AccessDeniedException {
//        TODO 将code 码改为枚举
        final String message = e.getMessage();
        return Result.error().code(e.getCode()).message(message);
    }
}
